<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!-- 搜索与添加 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="getUserInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 列表渲染 -->
      <el-table :data="userList" border="">
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"> </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUserById(scope.row.id)"></el-button>
            <el-tooltip effect="dark" content="分配权限" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="getUserInfo.pagenum"
        :page-sizes="[1, 2, 3, 10]"
        :page-size="getUserInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog title="提示" :visible.sync="addDialogVisible" width="40%" @close="addDialogClosed">
      <!-- form表单 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addconfirm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 这是修改用户的对话框 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="40%" @close="editDialogClosed">
      <!-- 修改表单区域 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
    title="提示"
    :visible.sync="setRoledialogVisible"
    width="40%" @close="setRoledialogClosed">
   <div>
     <p>当前的用户：{{userinfo.username}}</p>
     <p>当前的角色：{{userinfo.role_name}}</p>
     <p>分配新角色：
       <el-select v-model="selectedRoleId" placeholder="请选择">
      <el-option
        v-for="item in roleList"
        :key="item.id"
        :label="item.roleName"
        :value="item.id">
      </el-option>
    </el-select>
     </p>
   </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="setRoledialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="setRoleSave">确 定</el-button>
    </span>
  </el-dialog>
  </div>
</template>

<script>

export default {
  data() {
    // 邮箱验证规则
    var emailCheck = (rule, value, cb) => {
      const emailReg = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
      if (emailReg.test(value)) {
        return cb()
      }
      cb(new Error('邮箱地址不合法'))
    }
    // 手机号验证规则
    var mobileCheck = (rule, value, cb) => {
      const mobileReg = /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\d{8}$/
      if (mobileReg.test(value)) {
        return cb()
      }
      cb(new Error('请输入手机号的正确格式'))
    }
    return {
      // getUserList的参数
      getUserInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      // 用户列表
      userList: [],
      total: 0,
      // 这是控制添加对话框的显示和隐藏
      addDialogVisible: false,
      // 添加用户数据 对象
      addForm: {
        username: '',
        password: '',
        mobile: '',
        email: ''
      },
      // 这是添加用户 表单校验规则 对象
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: emailCheck, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: mobileCheck, trigger: 'blur' }
        ]
      },
      // 这是控制修改用户对话框的显示和隐藏
      editDialogVisible: false,
      // 修改用户信息的数据 对象
      editForm: {},
      // 修改用户数据 的校验规则 对象
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: emailCheck, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: mobileCheck, trigger: 'blur' }
        ]
      },
      // 这是即将要被分配权限  的  个人信息
      userinfo: {},
      // 这是全部角色的列表  数组
      roleList: [],
      // 这是控制 分配权限对话框的显示与隐藏
      setRoledialogVisible: false,
      // 已经选中的角色id值
      selectedRoleId: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 获取用户列表
    async getUserList() {
      const { data: res } = await this.$http.get('users', { params: this.getUserInfo })
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 每页显示多少条 this.pagesize 监听 pagesize 改变的事件
    handleSizeChange(newpage) {
      this.getUserInfo.pagesize = newpage
      this.getUserList()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newpage) {
      this.getUserInfo.pagenum = newpage
      this.getUserList()
    },
    // 状态码修改
    async userStateChange(userinfo) {
      console.log(userinfo)
      const { data: res } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('更新状态失败')
      }
      return this.$message.success('更新状态成功！')
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      //  重置按钮
      this.$refs.addFormRef.resetFields()
    },
    // 点击按钮，添加新用户
    addconfirm() {
      // 表单预校验
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return false
        // 验证通过可以发起添加用户的网络请求
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error('用户创建失败')
        this.$message.success('用户创建成功')
        // 添加表单区域隐藏
        this.addDialogVisible = false
        // 再刷新一下列表
        this.getUserList()
      })
    },
    // 展示 修改表单对话框
    async showEditDialog(id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询失败')
      }
      this.$message.success('查询成功')
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 监听修改用户对话框的关闭事件
    editDialogClosed() {
      //  重置按钮
      this.$refs.editFormRef.resetFields()
    },
    // 提交修改用户信息
    editConfirm() {
      // 提交之前的表单预验证
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return false
        // 发起修改用户信息的请求
        const { data: res } = await this.$http.put('users/' + this.editForm.id, { email: this.editForm.email, mobile: this.editForm.mobile })
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('修改数据失败')
        // 修改数据成功要做三步操作
        // 隐藏修改用户信息对话框
        this.editDialogVisible = false
        // 刷新列表
        this.getUserList()
        // 提示用户修改成功
        this.$message.success('修改用户信息成功')
      })
    },
    // 通过id删除用户
    async deleteUserById(id) {
      const deleteConfirmRes = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (deleteConfirmRes !== 'confirm') {
        return this.$message.info('已取消了删除')
      }
      // 确认删除
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      this.getUserList()
    },
    // 分配角色
    async setRole(role) {
      // 在分配权限对话框显示之前  先要拿到  即将要分配权限的数据
      // 拿到后存储在  data  上
      this.userinfo = role
      // 在分配权限对话框显示之前  还要拿到  全部的角色
      const { data: res } = await this.$http.get('roles')
      this.roleList = res.data
      console.log(res)
      console.log(this.roleList)
      this.setRoledialogVisible = true
    },
    // 监听 分配角色 对话框 的关闭事件
    setRoledialogClosed() {
      // alert(1)
      this.selectedRoleId = ''
      this.userinfo = ''
    },
    // 提交分配角色 表单
    async setRoleSave() {
      if (!this.selectedRoleId) return this.$message.error('请分配新角色')
      const { data: res } = await this.$http.put(`users/${this.userinfo.id}/role`, { rid: this.selectedRoleId })
      if (res.meta.status !== 200) return this.$message.error('设置角色失败')
      this.$message.success('设置角色成功')
      this.getUserList()
      this.setRoledialogVisible = false
    }
  }
}

</script>
<style lang="less" scoped></style>
